<?php

/**
 * Class to Identity User by Database Information.
 * 
 * 
 * @author Tuan Nguyen <nganhtuan63@gmail.com>
 * @version 1.0
 * @package cms.components.user
 */
class UserIdentityDb extends CUserIdentity {

    /**
     *
     * @var int Id of the User
     */
    private $_id;

    /**
     *
     * @var CActiveRecord current User Model
     */
    private $_model;

    /**
     * This function check the user Authentication 
     * 
     * @return int 
     */
    public function authenticate() {
        $username = strtolower($this->username);

        if (strpos($username, '@') !== false) {
            $user = User::model()->find('LOWER(email)=?', array($username));
        } else {
            $user = User::model()->find('LOWER(username)=?', array($username));
        }

        if ($user === null) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
        } else if (!$user->validatePassword($this->password)) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
        } else {
            if ($user->active == LGConstant::USER_STATUS_ACTIVE) {
                $this->_id = $user->id;
                $this->_model = $user;

                //Set the Error Code to None for Success
                $this->errorCode = self::ERROR_NONE;
            } else {
                $this->errorCode = LGConstant::USER_STATUS_NOT_ACTIVE;
            }
        }

        unset($user);

        return $this->errorCode;
    }

    /**
     * Return the property _id of the class
     * @return bigint
     */
    public function getId() {
        return $this->_id;
    }

    /**
     *
     * Return the _model of the class
     * @return CActiveRecord
     */
    public function getModel() {
        return $this->_model;
    }

}

?>